﻿using Hangfire;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
using System;
using System.IO;

namespace Web
{
    public class Startup
    { 
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();

            if (env.IsDevelopment())
            {
                // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
                builder.AddApplicationInsightsSettings(developerMode: true);
            }
            Configuration = builder.Build();             
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddAuthentication(options =>
            {
                options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
                 .AddCookie(options =>
                 {
                     options.ExpireTimeSpan = TimeSpan.FromHours(4);
                     options.LoginPath = new PathString("/Home/Login/");
                     options.LogoutPath = new PathString("/Home/Logout/");
                     options.AccessDeniedPath = new PathString("/Sys/Home/AccessDenied/");
                     options.SlidingExpiration = true;
                 });
            services.AddMvc();

            //使用Hangfire后台处理任务 注入Hnagfire服务
            string SqlServer = "Data Source=60.160.21.158,1433;Initial Catalog=ybsoft;Integrated Security=False;Persist Security Info=False;User ID=sa;Password=Yuan1977";
            services.AddHangfire(x => x.UseSqlServerStorage(SqlServer));
                       
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            //add NLog to ASP.NET Core
            //loggerFactory.AddNLog();
            //loggerFactory.ConfigureNLog("nlog.config");

            //后台处理任务
            var jobOptions = new BackgroundJobServerOptions
            {                
                WorkerCount = 1, //并发任务数
                ServerName = "ybsoft_hangfire",//服务器名称
            };
            app.UseHangfireServer(jobOptions);    //启用HangfireServer这个中间件（它会自动释放）
            app.UseHangfireDashboard(); //启用Hangfire的仪表盘（可以看到任务的状态，进度等信息）

            if (env.IsDevelopment())
            {
                //开发环境异常处理
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                //生产环境异常处理
                app.UseExceptionHandler("/Home/Error");
            }
            //404错误显示为：Status Code: 404; Not Found
            app.UseStatusCodePages();            

            //为了FileHelper类
            app.UseWkMvcDI();

            //使用静态文件，可以访问所有wwwroot目录下的静态文件
            app.UseStaticFiles();
            //使用静态文件，可以访问Views目录及子目录下的JS文件
            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(Directory.GetCurrentDirectory())
            });

            app.UseAuthentication();

            //使用Mvc，设置默认路由
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "areas",
                    template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
                  );
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{pageindex?}");
            });

           

        }        
    }

    
}
